<template>
  <div>
    <!-- 查询表单 -->
    <el-form :inline="true" class="mb-4">
      <el-form-item label="编码">
        <el-input v-model="query.code" style="width:200px" placeholder="请输入编码" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="query.status" placeholder="请选择状态" style="width:160px" clearable>
          <el-option label="全部" :value="null" />
          <el-option label="待审核" :value="1" />
          <el-option label="已审核" :value="2" />
          <el-option label="已驳回" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="单据日期：">
        <el-date-picker
          v-model="query.dateRange"
          type="daterange"
          range-separator="至"
          :start-placeholder="query.dateRange[0] || '开始'"
          :end-placeholder="query.dateRange[1] || '结束'"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchPage(1)">查询</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据列表 -->
    <TestPage
      @row-audit="openAudit"
      :table-data="list"
      :columns="columns"
      :current-page="page"
      :total="total"
      :page-size="size"
      @page-change="fetchPage"
      @action="handleTableAction"
      @edit="openEditDialog"
      @delete="handleDelete"
    />

    <!-- 审核对话框 -->
    <el-dialog
        v-model="auditVisible"
        title="单据审核"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form :model="auditForm" :rules="auditRules" ref="auditFormRef">
        <el-form-item label="单据编号：" prop="code">
          <el-input
              v-model="auditForm.code"
              disabled
              placeholder="系统自动填充"
          />
        </el-form-item>

        <el-form-item label="审核人：" prop="auditor">
          <el-select
              v-model="auditForm.auditor"
              placeholder="请选择审核人"
              filterable
              clearable
              style="width: 100%"
          >
            <el-option
                v-for="user in userList"
                :key="user.id"
                :label="`${user.name} `"
                :value="user.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="审批意见：" prop="comment">
          <el-input
              v-model="auditForm.comment"
              type="textarea"
              :rows="3"
              placeholder="请输入审批意见"
              maxlength="200"
              show-word-limit
          />
        </el-form-item>
        <el-form-item label="审核结果：" prop="checkResult">
          <el-select
              v-model="auditForm.checkRes"
              placeholder="请选择审核结果"
              style="width: 100%"
          >
            <el-option label="通过" :value="true" />
            <el-option label="不通过" :value="false" />
          </el-select>
        </el-form-item>

      </el-form>

      <template #footer>
        <el-button @click="auditVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">提交审核</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import request from '@/util/request'
import { ElMessageBox, ElMessage } from 'element-plus'
import TestPage from '@/test/TestPage.vue'
import { useRouter } from 'vue-router'
import type { ProMove, Good } from '@/types/kc/KCDB'
import type { User } from '@/types/rs/User';


// 分页 & 查询
const page = ref(1), size = ref(5), total = ref(0)
const list = ref<ProMove[]>([])
const query = reactive<{ code: string; status: number|null; dateRange: [string,string]|[] }>({
  code: '', status: null, dateRange: []
})

// 列定义
const columns = ref([
  { prop:'id',label:'ID' },
  { prop:'code',label:'编码' },
  { prop:'date',label:'单据日期' },
  { prop:'status',label:'状态' },
  { prop:'skname',label:'仓管人' },
  { prop:'delFlag',label:'删除状态' },
  { prop:'createDate',label:'创建时间' },
  { prop:'createUser',label:'创建人' },
  { prop:'updateDate',label:'更新时间' },
  { prop:'updateUser',label:'更新人' }
])

// 审核弹窗
const auditVisible = ref(false)
const auditFormRef = ref()
const auditForm = reactive({
  code: '',
  auditor: '',
  comment: '',
  checkRes: null
});
const auditRules = reactive({
  pass: [{ required: true, message: '请选择审核结果', trigger: 'change' }]
})
let current: ProMove|null = null

let userList=ref<User[]>([])
let selectUser=async()=>{
  let response=await request.post('per/user/getAll')
  userList.value=response.data.data
  console.log(userList.value)
}
selectUser()

// 时间格式
function fmtDate(d: Date, end=false){
  const z=(n:number)=>n.toString().padStart(2,'0')
  const Y=d.getFullYear(), M=z(d.getMonth()+1), D=z(d.getDate())
  return end?`${Y}-${M}-${D} 23:59:59`:`${Y}-${M}-${D} 00:00:00`
}

// 拉取分页
async function fetchPage(p:number){
  const ps=new URLSearchParams()
  ps.append('pageNow',p+''); ps.append('pageSize',size.value+'')
  if(query.code) ps.append('code',query.code)
  if(query.status!=null) ps.append('status',query.status+'')
  if(query.dateRange.length===2){
    const [s,e]=query.dateRange.map(x=>new Date(x))
    ps.append('startDate',fmtDate(s,false))
    ps.append('endDate',fmtDate(e,true))
  }
  const r=await request.post('kc/proMove/getProMovePage', ps)
  const d=r.data.data
  list.value=d.list||[]
  total.value=d.total||0
  page.value=d.pageNo||p
}

// 重置条件
function reset() {
  query.code = ''
  query.status = null
  query.dateRange = []
  fetchPage(1)
}

// 操作按钮
function handleTableAction(actionName: string) {
  if (actionName === 'add') {
    router.push({ name: 'Addkcdb' })
  }
}

// 编辑 & 删除
const router = useRouter()

function openEditDialog(row: ProMove) {
  router.push({ name: 'EditKCDB', params: { code: row.code } })
}

async function handleDelete(row: ProMove) {
  try {
    await ElMessageBox.confirm(
      '确定要删除该条记录吗？此操作不可恢复！',
      '警告',
      { type: 'warning' }
    )
    await request.post(
      'kc/proMove/delProMove',
      new URLSearchParams({ code: row.code }),
      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
    )
    ElMessage.success('删除成功')
    fetchPage(page.value)
  } catch (err) {
    if (err === 'cancel') {
      ElMessage.info('已取消删除')
    } else {
      ElMessage.error('删除失败')
      console.error(err)
    }
  }
}


// 打开审核框
function openAudit(row:ProMove){
  auditForm.code = row.code
  auditVisible.value = true
  console.log('当前审核单据:', row.code)
}

// 提交审核并生成出入库
async function submitAudit(){
  await auditFormRef.value.validate()
  // 1. 调拨审核
  await request.post('kc/proMove/check',{
         code: auditForm.code,
      typeId: 9,
      status: 3,
      checkManId: auditForm.auditor,  // 绑定审核人ID
      checkComment: auditForm.comment, // 绑定审批意见
      checkRes: auditForm.checkRes // 绑定审核结果
  })
  ElMessage.success('审核完成')
  auditVisible.value=false

  fetchPage(page.value)
}

// 首次加载
fetchPage(1)
</script>

<style scoped>
.mb-4 { margin-bottom:16px }
</style>

